package com.sangu.dianxiu.ui;

import android.content.Intent;
import android.database.DataSetObserver;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.android.volley.VolleyError;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.sangu.dianxiu.BaseApp;
import com.sangu.dianxiu.ICallBack;
import com.sangu.dianxiu.R;
import com.sangu.dianxiu.adapter.FrequentAddressAdapter;
import com.sangu.dianxiu.bean.user.AddAddressEntity;
import com.sangu.dianxiu.bean.user.AddressEntity;
import com.sangu.dianxiu.config.Constants;
import com.sangu.dianxiu.utils.UserManager;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.HashMap;

public class FrequentAddressActivity extends BaseActivity {

    private UserManager userManager=new UserManager();              //使用此类进行网络请求
    private ArrayList<AddressEntity.AddrsEntity> addrs=new ArrayList<>();       //地址数据
    private FrequentAddressAdapter addressAdapter;                      //地址列表adapter
    private MyDataSetObserver dataSetObserver=new MyDataSetObserver();      //adapter数据变化的观察者，
    private double lat;                                             //纬度
    private double lon;                                             //经度
    @ViewInject(R.id.iv_activity_frequentaddress_back)              //使用xutils的注解，这样就不用findviewbyid了
    private ImageView ivBack;
    @ViewInject(R.id.et_activity_frequentaddress_mapselect)
    private EditText etMapSelect;
    @ViewInject(R.id.et_activity_frequentaddress_countyselect)
    private EditText etCountySelect;
    @ViewInject(R.id.et_activity_frequentaddress_detailaddr)
    private EditText etDetailAddr;
    @ViewInject(R.id.btn_activity_frequentaddress_add_addr)
    private Button btnAddAddr;
    @ViewInject(R.id.lv_activity_frequent_address)
    private ListView lvAddress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_frequent_address);
        ViewUtils.inject(this);                     //加上这一行代码，上面的注解才会生效
        init();
        loadAddress();
    }
    private void init() {

        addressAdapter=new FrequentAddressAdapter(addrs,this);
        lvAddress.setAdapter(addressAdapter);

        lvAddress.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent=new Intent();
                intent.putExtra("addrId",addrs.get(position).getAddrId()+"");
                intent.putExtra("addr",addrs.get(position).getAddr());
                setResult(Constants.REQUEST_CODE_ADDRESS_SELECT, intent);               //这个是为了给下订单的时候选择地址用的
                FrequentAddressActivity.this.finish();
            }
        });
    }

    private void loadAddress() {
        HashMap<String,String> map=new HashMap<>();
        map.put("userId", BaseApp.user.getUserId() + "");
        map.put("cityId", 1 + "");
        userManager.getAddress(map, new ICallBack() {
            @Override
            public void onSuccess(String string) {
                AddressEntity entity = JSONObject.parseObject(string, AddressEntity.class);
                if (entity.getRc() == 0) {
                    addrs.addAll(entity.getAddrs());
                    addressAdapter.notifyDataSetChanged();
                    addressAdapter.registerDataSetObserver(dataSetObserver);                //给adapter设置观察者，这样当adapter的数据变化时，可以调整相应的listview的显示界面
                }
            }

            @Override
            public void onError(VolleyError error) {

            }
        });
    }

    class MyDataSetObserver extends DataSetObserver{
        @Override
        public void onChanged() {
            super.onChanged();
            addressAdapter.unregisterDataSetObserver(dataSetObserver);              //当加载数据的时候要取消观察者，否则会出现循环
            addrs.clear();
            loadAddress();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==Constants.REQUEST_CODE_MAP_SELECT)
        {
            if(data!=null)
            {
                String locAddress=data.getStringExtra("locAddress");
                lat=data.getDoubleExtra("lat",0);
                lon=data.getDoubleExtra("lon",0);
                if(locAddress!=null)
                {
                    etMapSelect.setText(locAddress);
                }

            }
        }
    }

    @OnClick({R.id.iv_activity_frequentaddress_back,R.id.tv_activity_frequentaddress_mapselect,R.id.tv_activity_frequentaddress_countyselect,
            R.id.btn_activity_frequentaddress_add_addr})
    public void onClick(View view)
    {
        Intent intent;
        switch (view.getId())
        {
            case R.id.iv_activity_frequentaddress_back:             //当点击返回图标的时候，结束此activity
                finish();
                break;
            case R.id.tv_activity_frequentaddress_mapselect:                //进行地图选择
                intent=new Intent(this,MapSelectActivity.class);
                startActivityForResult(intent, Constants.REQUEST_CODE_MAP_SELECT);
                break;
            case R.id.tv_activity_frequentaddress_countyselect:
                intent=new Intent(this,CountySelectActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_activity_frequentaddress_add_addr:

                submit();
                break;
        }
    }

    private void submit() {
        HashMap<String,String> map=new HashMap<>();
        map.put("userId",BaseApp.user.getUserId()+"");
        map.put("cityId",1+"");
        map.put("countyId",1+"");
        map.put("addr",etMapSelect.getText().toString());
        map.put("lon",lon+"");
        map.put("lat",lat+"");
        userManager.addAddress(map, new ICallBack() {
            @Override
            public void onSuccess(String string) {
                AddAddressEntity entity= JSONObject.parseObject(string,AddAddressEntity.class);
                if (entity.getRc() == 0)
                {
                    addrs.clear();
                    addressAdapter.unregisterDataSetObserver(dataSetObserver);              //当添加地址的时候取消观察者，否则会出现循环
                    //当添加地址成功后重新加载地址
                    loadAddress();

                }
            }

            @Override
            public void onError(VolleyError error) {

            }
        });
    }
    //当销毁Activity的时候取消网络请求，这也正是volley框架的优点之一
    @Override
    protected void onDestroy() {
        super.onDestroy();
        userManager.requestQueue.cancelAll(UserManager.class);
    }
}
